#!/bin/bash
#
# manage main web server

prog="node --max-old-space-size=4000"
args="analysis.js"
logs="web.log"

RETVAL=0
_start() {
    pidfile="web.pid"

    echo -n $"Starting $name .............."
    if [ -f $pidfile ]; then
        echo -e "\t\E[31;40m[FAIL]\033[0m"
        echo "web is Running"
    else
        $prog $args >>$logs 2>&1 &
		echo $! > $pidfile
        sleep 1
        if [ -f $pidfile ]; then
            echo -e "\t\E[32;40m[OK]\033[0m"
        else
            echo -e "\t\E[31;40m[FAIL]\033[0m"
        fi
    fi
    RETVAL=$?
}

_stop() {
    pidfile="web.pid"

    echo -n $"Stopping web .............."
    if [ -f ${pidfile} ]; then
        pid=`cat ${pidfile}`
        if [ -d "/proc/${pid}" ]; then
            rm -f $pidfile
            while [ -d "/proc/${pid}" ]; do
                kill -9 ${pid}
                sleep 1
            done
        else
            rm -f ${pidfile}
        fi
    fi
    echo -e "\t\E[32;40m[OK]\033[0m"
    RETVAL=$?
}

_reload() {
    echo $"Reloading nothing ............"
    RETVAL=$?
}

_status() {
    pidfile="web.pid"

    if [ -f ${pidfile} ]; then
        pid=`cat ${pidfile}`
        if [ -d "/proc/${pid}" ]; then
            echo -e "\E[32;40m[Running]\033[0m"
        else
            echo -e "\E[31;40m[Lost]\033[0m"
        fi
    else
        echo -e "\E[31;40m[Stoped]\033[0m"
    fi

    RETVAL=$?
}

start() {
    cp -r ~/git/ssanguo/conf .
    _start
}

stop() {
    _stop
}

# See how we were called.
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  status)
        _status
        ;;
  restart)
        stop
        start
        ;;
  reload)
        _reload
        ;;
  *)
        echo $"Usage: manage {start|stop|restart|status|reload}"
        exit 1
esac

exit $RETVAL
